#include "BoardManager.h"
#include "board.h"
#include "Board.h"      // 包含BreakingBoard定义的文件
#include "SpikyBoard.h" // 添加尖刺板头文件
#include <iostream>
#include <algorithm>
#include <cmath>
#include <memory>
#include <cstdlib>
#include <ctime>

std::unique_ptr<Board> BoardManager::CreateBoardOfType(const std::string& type, float x, float y, const GameConfig& config) {
    if (type == "BreakingBoard") {
        return std::make_unique<BreakingBoard>(x, y, config); // 修复：创建BreakingBoard对象
    } else if (type == "SpikyBoard") {
        return std::make_unique<SpikyBoard>(x, y, config);
    } else {
        return std::make_unique<Board>(x, y, config);
    }
}

BoardManager::BoardManager() : maxBoards(0), lastBoardTime(0), boardFrequency(1000) {
    // 构造函数初始化列表
}

void BoardManager::Init(const GameConfig& gameConfig) {
    config = gameConfig;
    maxBoards = config.boardMaxCount;
    
    boards.clear();
    
    // 初始化固定数量的板子，按照downdown.cpp的方式分布
    for (int i = 0; i < maxBoards; i++) {
        float initialX, initialY;
        
        // 第一个板子在屏幕上方1/3位置，其余板子均匀分布
        if (i == 0) {
            initialY = rand() % (config.screenHeight / 3) + 50;
        } else {
            initialY = (i - 1) * 70 + config.screenHeight / 3 + 50; // 减小间距到70像素
        }
        
        initialX = rand() % (config.screenWidth - static_cast<int>(config.boardWidth));
        
        // 使用CreateBoardOfType创建相应类型的板子
        float randomValue = (float)rand() / RAND_MAX;
        float cumulativeProbability = 0.0f;
        
        bool typeSet = false;
        std::string boardType = "NormalBoard";
        for (const auto& pair : config.boardTypeProbabilities) {
            cumulativeProbability += pair.second;
            if (randomValue <= cumulativeProbability) {
                boardType = pair.first;
                typeSet = true;
                break;
            }
        }
        
        if (!typeSet) {
            boardType = "NormalBoard";
        }
        
        // 替换为正确类型的板子
        auto newBoard = CreateBoardOfType(boardType, initialX, initialY, config);
        newBoard->SetActive(true);
        boards.push_back(std::move(newBoard));
    }
    
    lastBoardTime = 0;
    boardFrequency = config.boardGenerationFrequency;
}

void BoardManager::Update() {
    // 更新所有板子
    for (auto& board : boards) {
        board->Update();
        
        // 如果板子移出屏幕顶端，则重新放置到屏幕底部
        if (board->GetPosition().y < -config.boardHeight) {
            float x = static_cast<float>(rand() % (config.screenWidth - static_cast<int>(config.boardWidth)));
            float y = config.screenHeight + 20.0f; // 从屏幕底部重新出现
            
            // 重置板子位置和类型
            board->Reset(x, y);
            
            // 随机设置板子类型
            float randomValue = (float)rand() / RAND_MAX;
            float cumulativeProbability = 0.0f;
            
            bool typeSet = false;
            std::string boardType = "NormalBoard";
            for (const auto& pair : config.boardTypeProbabilities) {
                cumulativeProbability += pair.second;
                if (randomValue <= cumulativeProbability) {
                    boardType = pair.first;
                    typeSet = true;
                    break;
                }
            }
            
            if (!typeSet) {
                boardType = "NormalBoard";
            }
            
            // 由于我们无法直接改变unique_ptr指向的对象类型，
            // 我们需要替换整个对象
            auto newBoard = CreateBoardOfType(boardType, x, y, config);
            newBoard->SetActive(true);
            
            // 替换向量中的元素
            // 找到当前board在向量中的位置
            auto it = std::find_if(boards.begin(), boards.end(), 
                                 [&board](const std::unique_ptr<Board>& b) { 
                                     return b.get() == board.get(); 
                                 });
            if (it != boards.end()) {
                *it = std::move(newBoard);
            }
        }
    }
}

void BoardManager::Draw() {
    // 绘制所有板子（活跃的）
    for (auto& board : boards) {
        // 移除活跃状态检查，确保所有板子都被绘制
        board->Draw();
    }
}

void BoardManager::SetFrequency(int frequency) {
    boardFrequency = frequency;
}

std::vector<Board*> BoardManager::GetActiveBoards() {
    std::vector<Board*> activeBoards;
    for (auto& board : boards) {
        if (board->IsActive()) {
            activeBoards.push_back(board.get());
        }
    }
    return activeBoards;
}

void BoardManager::ResetBoards() {
    // 重置所有板子到初始状态
    for (int i = 0; i < maxBoards; i++) {
        float initialX, initialY;
        
        // 第一个板子在屏幕上方1/3位置，其余板子均匀分布
        if (i == 0) {
            initialY = rand() % (config.screenHeight / 3) + 50;
        } else {
            initialY = (i - 1) * 70 + config.screenHeight / 3 + 50; // 减小间距到70像素
        }
        
        initialX = rand() % (config.screenWidth - static_cast<int>(config.boardWidth));
        
        // 重置板子位置
        boards[i]->Reset(initialX, initialY);
        boards[i]->SetActive(true);
        
        // 随机设置板子类型
        float randomValue = (float)rand() / RAND_MAX;
        float cumulativeProbability = 0.0f;
        
        bool typeSet = false;
        std::string boardType = "NormalBoard";
        for (const auto& pair : config.boardTypeProbabilities) {
            cumulativeProbability += pair.second;
            if (randomValue <= cumulativeProbability) {
                boardType = pair.first;
                typeSet = true;
                break;
            }
        }
        
        if (!typeSet) {
            boardType = "NormalBoard";
        }
        
        // 替换为正确类型的板子
        auto newBoard = CreateBoardOfType(boardType, initialX, initialY, config);
        newBoard->SetActive(true);
        boards[i] = std::move(newBoard);
    }
    
    // 重置时间，确保游戏开始时立即生成板子
    lastBoardTime = GetTime() * 1000;
}